package com.woniuxy.coachdao.config;

import com.woniuxy.coachdao.mapper.CoachLoginLogMapper;
import com.woniuxy.coachdao.model.CoachLoginLog;
import com.woniuxy.util.MyRedisKeyUtil;
import com.woniuxy.util.MyRedisUtil;
import com.woniuxy.util.MySmsUtil;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class CodeConsumer {
    @Autowired
    private MySmsUtil mySmsUtil;
    @Autowired
    private MyRedisUtil myRedisUtil;
    @Autowired
    private MyRedisKeyUtil myRedisKeyUtil;
    @Autowired
    private CoachLoginLogMapper coachLoginLogMapper;
    @RabbitHandler
    @RabbitListener(queuesToDeclare = {@Queue(value = "coach_code_send_register")})
    public void codeSendRegister(String phone) throws Exception {
        String phoneCode = mySmsUtil.send(phone);//通过互亿验证码发送工具生成验证码，发送短信并返回
        //缓存里的key要具有可识别度，唯一性，规范
        myRedisUtil.set(myRedisKeyUtil.registerCodeKey(phone),phoneCode,5*60);//验证码有效期5分钟
        myRedisUtil.set(myRedisKeyUtil.sendRegisterInMinute(phone),"0",60);//限制注册一分钟内不能重复发
        if (!myRedisUtil.exists(myRedisKeyUtil.sendCodeTotalInHour(phone))){
            myRedisUtil.set(myRedisKeyUtil.sendCodeTotalInHour(phone),"1",60*60);
        }else {
            myRedisUtil.increment(myRedisKeyUtil.sendCodeTotalInHour(phone));//1小时内验证发送次数
        }
    }

    @RabbitHandler
    @RabbitListener(queuesToDeclare = {@Queue(value = "coach_code_send_login")})
    public void codeSendLogin(String phone) throws Exception {
         String phoneCode = mySmsUtil.send(phone);//通过互亿验证码发送工具生成验证码，发送短信并返回
        //缓存里的key要具有可识别度，唯一性，规范
        myRedisUtil.set(myRedisKeyUtil.loginCodeKey(phone),phoneCode,5*60);//验证码有效期5分钟
        myRedisUtil.set(myRedisKeyUtil.sendLoginInMinute(phone),"0",60);//限制登录一分钟内不能重复发
        if (!myRedisUtil.exists(myRedisKeyUtil.sendCodeTotalInHour(phone))){
            myRedisUtil.set(myRedisKeyUtil.sendCodeTotalInHour(phone),"1",60*60);
        }else {
            myRedisUtil.increment(myRedisKeyUtil.sendCodeTotalInHour(phone));//1小时内验证发送次数
        }
    }


    @RabbitHandler
    @RabbitListener(queuesToDeclare = {@Queue(value = "coach_login_log")})
    public void coachLoginLog(CoachLoginLog coachLoginLog) throws Exception {
       coachLoginLogMapper.insert(coachLoginLog);
    }
}
